<?php

namespace app\index\controller;

use think\Controller;
use think\Request;

class Goods extends Base
{
    //
    public function index(int $id)
    {

        if(!is_int($id)){
            $this->error("类型错误","/index/index/index");
        }

        $title = "商品列表页";

        // 获取当前的分类id
        $cate = \app\index\model\Category::where('id',$id)->order('id','ASC')->find();

        // 查询当前分类所有的商品
        $goods = \app\index\model\Goods::where("cate_id",$cate['id'])->select();


        return view("/goods/list",[
            'title' => $title,
            'cate' => $cate,
            'goods' => $goods
        ]);
    }

    // 商品详情
    public function goodsItem(int $id)
    {
        if(!is_int($id)){
            $this->error("类型错误","/index/index/index");
        }

        $title = "商品详情页";

        // 查询当前商品分类
        $three = \app\index\model\Goods::find($id);
        $three_id = \app\index\model\Category::where('id',$three['cate_id'])->find();
        // 查询二级分类id
        $two_id = \app\index\model\Category::where('id',$three_id['pid'])->find();
        // 查询一级分类id
        $one_id = \app\index\model\Category::where('id',$two_id['pid'])->find();

        // 查询当前的商品信息
        $goods = \app\index\model\Goods::find($id);

        // 获取当前商品信息的所有图片
        $goods_pics = \app\index\model\GoodsPics::where('goods_id',$id)->select();

        // 查询当前商品共有那些属性
        $attr = \app\index\model\Attribute::where("type_id",$goods['type_id'])->select();

        // 查询当前商品拥有的属性值
        $goods_attr = \app\index\model\GoodsAttr::where('goods_id',$id)->order('id','ASC')->select();

        // 将所有的属性值按照属性id分组
        $new_attr = [];
        foreach($goods_attr as $v)
        {
            $new_attr[$v['attr_id']][] = $v->toArray();
        }

        return view("/goods/item",[
            'title' => $title,
            'three_id' => $three_id,
            'two_id' => $two_id,
            'one_id' => $one_id,
            'goods' => $goods,
            'goods_pics' => $goods_pics,
            'attr' => $attr,
            'new_attr' => $new_attr
        ]);
    }

}
